import todoloc from "../components/utils/index"
export default {
    namespaced: true,
    state: {
        TodoArr: todoloc.get(),
        visibility: 'all',
        total: 0
    },
    mutations: {
        //新增数据
        SET_TODOARR(state, text) {
            state.TodoArr.push({
                text,
                completed: false
            })
        },
        AMEND(state, { todo, text = todo.text, completed = todo.completed }) {
            let ind = state.TodoArr.indexOf(todo)
            state.TodoArr.splice(ind, 1, {
                ...todo,
                text, //覆盖(原来的值)
                completed
            })
        },
        // 删除
        REMOVE(state, todo) {
            let ind = state.TodoArr.indexOf(todo)
            state.TodoArr.splice(ind, 1)
        },
        // 过滤
        AMEND_VIS(state, vis) {
            state.visibility = vis

        }
    },
    actions: {
        // 添加
        addlist({ commit }, text) {
            commit('SET_TODOARR', text)
        },
        // 修改
        amendTex({ commit }, { todo, text }) {
            commit('AMEND', { todo, text })
        },
        //删除
        remove({ commit }, todo) {
            commit("REMOVE", todo)
        },
        // 选中状态
        amendChk({ commit }, todo) {
            commit('AMEND', { todo, completed: !todo.completed })
        },
        // 全选
        amendAll({ commit, state }, Allcompleted) {
            state.TodoArr.forEach(todo => {
                commit('AMEND', { todo, completed: Allcompleted })
            });
        },
        // 过滤
        filter({ commit }, vis) {
            commit('AMEND_VIS', vis)
        },
        // 删除已完成的数据
        removeChk({ commit, state }) {
            state.TodoArr.filter(v => v.completed).forEach(todo=>{
                commit("REMOVE", todo)
            })
        }
    },
    getters: {
        NewArr(state) {
            if (state.visibility === 'all') {
                return state.TodoArr
            } else if (state.visibility === 'active') {
                return state.TodoArr.filter(v => !v.completed)
            } else {
                return state.TodoArr.filter(v => v.completed)
            }
        },
        total(state) {
            return state.TodoArr.filter(v => !v.completed).length
        }

    }
}